using System.Net;
using System.Text;

namespace muduoDotNet.Examples
{
    public class EchoClientExample
    {
        public static void RunExample()
        {
            Main(new string[0]);
        }
        
        static void Main(string[] args)
        {
            Logger.Info("Echo Client Started");
            
            // 创建事件循环
            var loop = new EventLoop();
            
            // 创建TCP客户端
            var client = new TcpClient(loop, new IPEndPoint(IPAddress.Loopback, 9999));
            
            // 设置连接回调
            client.ConnectionCallback = (conn) =>
            {
                if (conn != null)
                {
                    Logger.Info("Connected to server");
                    
                    // 连接成功后发送一条消息
                    client.Send("Hello, Echo Server!");
                }
                else
                {
                    Logger.Warning("Failed to connect to server");
                }
            };
            
            // 设置消息回调
            client.MessageCallback = (conn, buffer) =>
            {
                // 读取消息
                string message = Encoding.UTF8.GetString(buffer.ReadAll());
                
                Logger.Info($"Received: {message}");
                
                // 停止客户端
                Task.Run(() =>
                {
                    Thread.Sleep(1000);
                    client.Disconnect();
                    loop.Stop();
                });
            };
            
            // 连接服务器
            client.Connect();
            
            Logger.Info("Connecting to server...");
            
            // 运行事件循环
            loop.Start();
            
            // 清理资源
            client.Dispose();
            loop.Dispose();
            
            Logger.Info("Echo Client Stopped");
        }
    }
}